﻿#region File and License Information
/*
<File>
	<License>
		Copyright © 2009 - 2017, Daniel Vaughan. All rights reserved.
		This file is part of Calcium (http://calciumsdk.net), 
		which is released under the MIT License.
		See file /Documentation/License.txt for details.
	</License>
	<CreationDate>2010-09-13 16:59:50Z</CreationDate>
</File>
*/
#endregion
/* Original source from http://www.codeproject.com/KB/cs/maybemonads.aspx */
using System;

namespace Outcoder.Functional
{
	public static class ObjectMonadExtensions
	{
		public static TResult With<TInput, TResult>(
			this TInput input, Func<TInput, TResult> evaluator) 
			where TResult : class where TInput : class
		{
			if (input == null)
			{
				return null;
			}
			return evaluator(input);
		}

		public static TResult With<TInput, TResult>(
			this TInput input, Func<TInput, TResult> evaluator, TResult resultIfInputNull) 
			where TInput : class
		{
			if (input == null)
			{
				return resultIfInputNull;
			}
			return evaluator(input);
		}

		public static TInput If<TInput>(this TInput input, Func<TInput, bool> evaluator) 
			where TInput : class
		{
			if (input == null)
			{
				return null;
			}
			return evaluator(input) ? input : null;
		}

		public static TInput Unless<TInput>(this TInput input, Func<TInput, bool> evaluator) 
			where TInput : class
		{
			if (input == null)
			{
				return null;
			}
			return evaluator(input) ? null : input;
		}

		public static TInput Do<TInput>(this TInput input, Action<TInput> action) 
			where TInput : class
		{
			if (input == null)
			{
				return null;
			}
			action(input);
			return input;
		}
	}
}
